<template>
  <div class="params">
     <!-- 面包屑导航 -->
      <bread :item="['商品管理','分类参数']"></bread>
    <!-- 卡片视图 -->
    <el-card shadow="hover">
      <!-- 头部警示 -->
      <el-alert
        title="注意:只允许第三级分类设置相关参数!"
        type="warning" show-icon >
      </el-alert>
      <!-- 选着商品分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选着商品分类 : </span>
          <!-- 选着商品的级联 -->
          <el-cascader
            v-model="cateKeys"
            :options="cates"
            :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name',children:'children' }"
            @change="handleChange"></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页 -->
      
         <el-tabs v-model="activeName" @tab-click="handleTabClick(self)">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="koy" @click="addDialog=true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTables" border stripe height="370" > 
            <!-- 展开行 -->
            <el-table-column type="expand" width="50">
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">
                  {{item}}
                </el-tag>
                 <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button icon="el-icon-edit" size="mini" type="primary" @click="visibleEditDia(scope.row.attr_id)"></el-button>
                <el-button icon="el-icon-delete" size="mini" type="danger" @click="removeParam(scope.row.attr_id)"></el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="koy" @click="addDialog=true">添加属性</el-button>
         
          <el-table :data="onlyTable" border stripe height="370"> 
            <!-- 展开行 -->
            <el-table-column type="expand" width="50">
              <template slot-scope="scope">
                <!-- 循环渲染tag -->
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button icon="el-icon-edit" size="mini" type="primary" @click="visibleEditDia(scope.row.attr_id)"></el-button>
                <el-button icon="el-icon-delete" size="mini" type="danger" @click="removeParam(scope.row.attr_id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
  
        </el-tab-pane>
      </el-tabs>
     
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialog"
      width="50%" @close="addDiaColse">
      <!-- 添加参数表单 -->
      <el-form :model="addForm" :rules="addRoles" ref="addForm" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editDialog"
      width="50%" @close="editDiaColse">
      <!-- 修改参数表单 -->
      <el-form :model="editForm" :rules="addRoles" ref="editForm" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {bread, default as fn} from "tools"
export default {
  components:{
    bread
  }
 ,data(){return{
    self:this
    //商品分类列表
    ,cates:[]
    //选中的级联id
   ,cateKeys:[]
   //tab的数据绑定
   ,activeName:'many'
   //动态参数数据
   ,manyTables:[]
   //静态属性的数据
   ,onlyTable:[]
   //显示添加参数的对话框
   ,addDialog:false
   //添加表单的绑定数据
   ,addForm:{
     attr_name:""
   }
   //添加表单的数据验证
   ,addRoles:{
     attr_name:[
       {required:true,message:"请输入属性",trigger:"blur"}
     ]
   }
   //修改对话框的显示
   ,editDialog:false
   //修改对话框的数据
   ,editForm:{
     attr_name:""
   }
  }}
 ,created(){
   this.getCates()
 }
 ,computed:{
   koy:i=> i.cateKeys.length!==3
  ,cateId(i){
    if(i.cateKeys.length!==3) return null
    return i.cateKeys[2]
  }
  ,titleText(s){
    return [s.activeName==="many" ?"动态" : "静态","属性"].join("")
  }
  
 }
 ,methods:{
   async getCates(){
     let {data:ret}= await this.$XHR.get('categories')
     if(ret?.meta?.status!==200)return fn.mg("error","出错了！")
      this.cates= ret?.data ? ret.data : []
   }
  ,async getParams(){
    let key= this.cateKeys
    if(key.length!==3){
      this.cateKeys=[]
      this.manyTables=[]
      this.onlyTable=[]
      return
    }
    //获取对应的参数，根据级联id
    let {data:ret}= await this.$XHR.get("categories/"+this.cateId+"/attributes",{params:{sel:this.activeName}})
    if(ret?.meta?.status!==200)return fn.mg("error","获取失败")
    //存储到对应表格
    ret.data.forEach(item=>{
      item.attr_vals =item.attr_vals?item.attr_vals= item.attr_vals.split(' '):[]
      //控制文本框的是否显示
      item.inputVisible= false
      //文本的内容绑定
      item.inputValue= ""
    })
    if(this.activeName==="many")this.manyTables=ret?.data ? ret.data : [];
    else this.onlyTable= ret?.data ? ret.data :[]
  }
  //级联选择器改变时触发
  ,handleChange(){
    this.getParams()
    
  }
  //点击tab面板时触发
  ,handleTabClick:(()=>{
    let active=""
    return (s)=>{
      if(active===s.activeName || !s.cateId)return
      active= s.activeName
      s.getParams()
      
    }
   
  })()
  //对话框关闭触发
  ,addDiaColse(){
    this.$refs['addForm'].resetFields()
  }
  //添加属性
  ,addParams(){
    this.$refs['addForm'].validate(async valid=>{
      if(!valid)return
      let {data:ret}= await this.$XHR.post("categories/"+this.cateId+"/attributes",{
        attr_name:this.addForm.attr_name
       ,attr_sel:this.activeName
      })
      if(ret?.meta?.status!==201)return fn.mg('error');
      fn.mg("success")
      this.addDialog= false
      this.getParams()
    })
  }
  ,async visibleEditDia(id){
    //查询当前参数的信息
    let {data:ret}= await this.$XHR.get('categories/'+this.cateId+'/attributes/'+id,{
      params:{attr_sel: this.activeName}
    })
    if(ret?.meta?.status!==200)return fn.mg("error")
    this.editForm= ret?.data ? ret.data : {}
    this.editDialog=true
  }
  //重置修改表单
  ,editDiaColse(){
    this.$refs['editForm'].resetFields()
  }
  ,editParams(){
    this.$refs['editForm'].validate(async valid=>{
      if(!valid)return
      let {data:ret}= await this.$XHR.put('categories/'+this.cateId+'/attributes/'+this.editForm.attr_id,{
        attr_name:this.editForm.attr_name
       ,attr_sel:this.activeName
      })
      if(ret?.meta?.status!==200)return fn.mg("error")
      fn.mg('success')
      this.getParams()
      this.editDialog=false
    })
  }
  ,removeParam(id){
    this.$confirm("这是永久删除","提示",{
      confirmButtonText:"确定"
     ,cancelButtonText:"取消"
     ,type:"warning"
    })
    .then(async()=>{
      let {data:ret}= await this.$XHR.delete('categories/'+this.cateId+'/attributes/'+id)
      if(ret?.meta?.status!==200)return fn.mg("error","删除失败")
      fn.mg("success","删除成功")
      this.getParams()
    },()=>{})
  }
  //文本框触发
  ,handleInputConfirm(n){
    //输入空会被清除
    if(n.inputValue.trim().length===0){
      n.inputValue=""
      n.inputVisible= false
      return
    }
    //输入合法
    n.attr_vals.push(n.inputValue.trim())
    n.inputValue=""
    n.inputVisible=false
    //调入保存函数
    this.putTag(n,'添加')
  }
  //显示文本框
  ,showInput(n){
    n.inputVisible= true
    //当页面上的元素被重新渲染之后，才会执行回调
    this.$nextTick(_=>{
      this.$refs['saveTagInput'].focus()
    })
  }
  //根据索引删除tag标签
  ,handleClose(i,n){
    n.attr_vals.splice(i,1)
    //调入保存函数
    this.putTag(n,'修改')
  }
  //发起请求保存attr_vals数据
  ,async putTag(n,p){   
    let {data:ret}= await this.$XHR.put('categories/'+this.cateId+'/attributes/'+n.attr_id,{
      attr_name:n.attr_name
     ,attr_sel:n.attr_sel
     ,attr_vals:n.attr_vals.join(" ")
    })
    //添加失败后消除添加的Tag
    if(ret?.meta?.status!==200){
      n.attr_vals.pop()
      return fn.mg('error',p+'失败')
    }
    fn.mg('success',p+"成功")
  }
 }
}
</script>

<style lang="less" scoped>
.params{
  .el-card{
    .cat_opt{
      margin: 15px 0;
    }
    .el-table{
      margin-top:15px;
      .el-tag{
        margin: 5px;
      }
      .input-new-tag{
        width: 120px;
      }
    }
  }
}
</style>